package com.zxy.ziems.server.file.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxy.btp.common.response.JsonResponse;
import com.zxy.btp.redis.utils.RedisUtil;
import com.zxy.btp.security.annotation.IgnoreLogin;
import com.zxy.ziems.server.file.dto.FileDto;
import com.zxy.ziems.server.file.service.FileService;
import com.zxy.ziems.server.file.vo.FileVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 文件上传管理
 * @author chdzq
 * @create 2023/3/21
 */
@RequestMapping("/api")
@RestController
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private RedisUtil redisUtil;

    public static final String web_cache_json_file_ = "web_cache_json_file_";

    public FileController() {
    }

    /**
     * 创建文件
     * @param dto
     * @return
     * @throws Exception
     */
    @PostMapping({"/file/add"})
    public JsonResponse<FileVO> add(@Validated @RequestBody FileDto dto) throws Exception {
        FileVO fileVO = this.fileService.add(dto);
        return JsonResponse.SUCCESS(fileVO);
    }

    /**
     * 上传文件
     * @param id 文件id
     * @param file 文件
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping({"/file/upload"})
    public JsonResponse<FileVO> upload(@RequestParam String id, @RequestParam(required = false) MultipartFile file, HttpServletRequest request) throws Exception {
        FileVO fileVO = this.fileService.upload(id, file, request);
        return JsonResponse.SUCCESS(fileVO);
    }

    /**
     * 预览及下载文件
     * @param response
     * @param id 文件id
     * @param isOnline 是否在线预览
     * @throws UnsupportedEncodingException
     */
    @GetMapping({"/file/download"})
    @IgnoreLogin
    public void download(HttpServletResponse response, @RequestParam String id, @RequestParam(required = false) Boolean isOnline) throws UnsupportedEncodingException {
        if (Objects.isNull(isOnline)) {
            isOnline = false;
        }
        this.fileService.downloadById(id, isOnline, response);
    }

    /**
     * 上传缓存文件
     * @param file 文件
     * @return
     * @throws Exception
     */
    @PostMapping({"/file/uploadJson"})
    public JsonResponse<FileVO> uploadCacheJson(@RequestParam MultipartFile file) throws Exception {
        // 读取文件内容
        String content = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))
                .lines().collect(Collectors.joining("\n"));
        try {
            JSONObject jsonObject = JSON.parseObject(content);

            redisUtil.set(web_cache_json_file_, jsonObject);
            return JsonResponse.SUCCESS(jsonObject);
        } catch (Exception e) {
            return JsonResponse.ERROR("非json格式");
        }
    }

    /**
     * 获取上传缓存数据
     * @return
     * @throws Exception
     */
    @PostMapping({"/file/getJson"})
    public JsonResponse<FileVO> getCacheJson() throws Exception {
        JSONObject o = (JSONObject) redisUtil.get(web_cache_json_file_);
        return JsonResponse.SUCCESS(o);
    }

    /**
     * 根据id查看文件的基本信息
     * @param id 文件id
     * @return
     * @throws Exception
     */
    @GetMapping({"/file/info"})
    public JsonResponse<FileVO> viewById(@RequestParam(required = true) String id) throws Exception {
        FileVO vo = this.fileService.viewById(id);
        return JsonResponse.SUCCESS(vo);
    }
}

